package ihm;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

public class Dessin extends JPanel{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	int xd,yd;
	BufferedImage dbimage;
	boolean imageInit=false;
	Graphics2D gim;
	public Dessin(){
		this.addMouseListener(new Appui());
		this.addMouseMotionListener(new Drag());
	}
	
	public void initBi(){
		if(!imageInit){
			dbimage=new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
			gim=dbimage.createGraphics();
			imageInit=true;
		}		
	}

	public void reset(){
		Graphics g = getGraphics();
		g.clearRect(0, 0, this.getSize().width, this.getSize().height );
		gim.clearRect(0, 0, this.getSize().width, this.getSize().height );
		this.setBackground(Color.WHITE);
		this.repaint();
	}
	
	
	public BufferedImage createImage() {
		return dbimage;
	}

class Drag implements MouseMotionListener {

		@Override
		public void mouseDragged(MouseEvent e) {
			// TODO Auto-generated method stub
			int x = e.getX();
			int y = e.getY();
			initBi();
			Graphics g = getGraphics();
			g.drawLine(xd-1, yd+1, x-1, y+1);
			g.drawLine(xd-1, yd, x-1, y);
			g.drawLine(xd-1, yd-1, x, y-1);
			g.drawLine(xd, yd+1, x, y+1);
			g.drawLine(xd, yd, x, y);
			g.drawLine(xd, yd-1, x-1, y-1);
			g.drawLine(xd+1, yd+1, x+1, y+1);
			g.drawLine(xd+1, yd, x+1, y);
			g.drawLine(xd+1, yd-1, x+1, y-1);
//
			gim.drawLine(xd-1, yd+1, x-1, y+1);
			gim.drawLine(xd-1, yd, x-1, y);
			gim.drawLine(xd-1, yd-1, x, y-1);
			gim.drawLine(xd, yd+1, x, y+1);
			gim.drawLine(xd, yd, x, y);
			gim.drawLine(xd, yd-1, x-1, y-1);
			gim.drawLine(xd+1, yd+1, x+1, y+1);
			gim.drawLine(xd+1, yd, x+1, y);
			gim.drawLine(xd+1, yd-1, x+1, y-1);
			xd=x;
			yd=y;

		}
		@Override
		public void mouseMoved(MouseEvent e) {
			// TODO Auto-generated method stub

		}
	}
	class Appui implements MouseListener{

		@Override
		public void mouseClicked(MouseEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void mouseEntered(MouseEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void mouseExited(MouseEvent e) {
			// TODO Auto-generated method stub

		}

		@Override
		public void mousePressed(MouseEvent e) {
			// TODO Auto-generated method stub
			xd=e.getX();
			yd=e.getY();
		}

		@Override
		public void mouseReleased(MouseEvent e) {
			// TODO Auto-generated method stub

		}

	}
}
